package net.siren93.smh.dao.impl;

import net.siren93.smh.dao.TaskDao;
import net.siren93.smh.entity.TaskEntity;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by siren93 on 15/10/11.
 */
@Repository("taskDao")
public class TaskDaoImpl implements TaskDao {

    @Autowired
    SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public TaskEntity findByName(String name) {
        String hql = "from TaskEntity as entity where entity.name=:name";
        Query query = getCurrentSession().createQuery(hql);
        query.setString("name", name);
        List<TaskEntity> list = query.list();
        if(list == null || list.size() == 0) {
            return null;
        } else {
            return list.get(0);
        }
    }

    @Override
    public List<TaskEntity> findByEmployee(int id, int page, int rows) {
        String hql = "from TaskEntity as entity where entity.employeeId=:id";
        Query query = getCurrentSession().createQuery(hql);
        query.setInteger("id", id);
        query.setFirstResult((page - 1) * rows);
        query.setMaxResults(rows);
        return query.list();
    }

    @Override
    public List<TaskEntity> findByProject(int id, int page, int rows) {
        String hql = "from TaskEntity as entity where entity.projectId=:id";
        Query query = getCurrentSession().createQuery(hql);
        query.setInteger("id", id);
        query.setFirstResult((page - 1) * rows);
        query.setMaxResults(rows);
        return query.list();
    }

    @Override
    public TaskEntity load(Integer id) {
        return (TaskEntity)getCurrentSession().load(TaskEntity.class, id);
    }

    @Override
    public TaskEntity get(Integer id) {
        return (TaskEntity)getCurrentSession().get(TaskEntity.class, id);
    }

    @Override
    public List<TaskEntity> findAll() {
        return getCurrentSession().createQuery("from TaskEntity").list();
    }

    @Override
    public void persist(TaskEntity entity) {
        getCurrentSession().persist(entity);
    }

    @Override
    public Integer save(TaskEntity entity) {
        return (Integer)getCurrentSession().save(entity);
    }

    @Override
    public void saveOrUpdate(TaskEntity entity) {
        getCurrentSession().saveOrUpdate(entity);
    }

    @Override
    public void delete(Integer id) {
        TaskEntity entity = load(id);
        getCurrentSession().delete(entity);
    }

    @Override
    public void flush() {
        getCurrentSession().flush();
    }
}
